<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace app\controller\wechat;

use think\App;
use hiduoke\services\WechatService;
use app\common\model\wechat\WechatUser;
use app\common\controller\WechatController;
use think\facade\Cache;
use think\facade\Cookie;
use think\facade\Log;
use think\facade\Session;

class Oauth extends WechatController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function callBack()
    {
        $WechatUser = new WechatUser();
        $WechatService = new WechatService();
        $plaid = get_plaid();
        $topuid = input('topuid', Cookie::get('dk_topuid', 0));
        if (!$plaid) {
            die('plaid不存在');
        }
        if (Cache::get($this->getKey('scopes')) == 'snsapi_base') {
            //静默授权
            $user = $WechatService->getApp()->oauth->scopes(['snsapi_base'])->userFromCode(input('code', ''))->toArray();
            $wx_user = array(
                'openid' => $user['id']
            );
            Cache::set($this->getKey('wx_user'), $wx_user);
        } else {
            //正常授权
            $user = $WechatService->getApp()->oauth->userFromCode(input('code', ''))->toArray();
            $is_snapshotuser = $user['token_response']['is_snapshotuser'] ?? 0;
            if ($is_snapshotuser != 1) {
                $original = $user['raw'];
                $wechat_user = $WechatUser->where(['openid' => $original['openid'], 'plaid' => $plaid])->findOrEmpty();
                $user_data = array(
                    'nickname'   => $user['nickname'],
                    'avatar'     => $user['avatar'],
                    'sex'        => $original['sex'],
                    'language'   => $original['language'],
                    'city'       => $original['city'],
                    'province'   => $original['province'],
                    'country'    => $original['country'],
                    'last_addon' => input('addon', '')
                );
                if ($wechat_user->isEmpty()) {
                    //写入用户信息
                    $user_insert_data = array(
                        'openid'      => $original['openid'],
                        'unionid'     => '',
                        'remark'      => '',
                        'plaid'       => $plaid,
                        'topuid'      => $topuid,
                        'teamuid'     => $topuid,
                        'first_addon' => input('addon', '')
                    );
                    $user_insert_data = array_merge($user_data, $user_insert_data);
                    $wechat_user->save($user_insert_data);
                } else {
                    //更新用户信息
                    $WechatService->clearUpdateWechat($wechat_user['id']);
                }
                session('openid', $wechat_user->openid);
                Cache::set($this->getKey('wx_user'), $wechat_user->toArray());
            }
        }

        $target_url = Cache::get($this->getKey('target_url'));

        if (!$target_url) {
            return showMessage('授权出现错误，请重试！', 'error', '', -1, ['show_btn' => false]);
        }
        if (strpos($target_url, '&wxref=mp.weixin.qq.com')) {
            $target_url = str_replace('&wxref=mp.weixin.qq.com', '', $target_url) . '&wxref=mp.weixin.qq.com#wechat_redirect';
        } else {
            $target_url .= '&wxref=mp.weixin.qq.com#wechat_redirect';
        }
        to($target_url);
    }

    protected function getKey($string)
    {
        return $string . input('sid') . '_' . input('p');
    }
}
